﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using DeepTalkRenderServiceLib;

namespace DeepTalkRenderShell.App.TalkRendering
{
    /// <summary>
    /// Helper functions that will aid in taking the input xml fiel from the rendering job and turn it into
    /// the info that is required by our code. :-)
    /// </summary>
    static class RenderMetaDataReturnHelpers
    {
        /// <summary>
        /// Given a pointer to an XML file, load it into a job meta data. Once we have that, put it 
        /// into the render results for use by the rest of the system.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static RenderMeetingTask.RenderResultsInfo ConvertToRenderResults(this FileInfo file)
        {
            ///
            /// Load the data from the file
            /// 

            if (!file.Exists)
            {
                throw new ArgumentException("THe file " + file.FullName + " does not exist!");
            }

            DeeptalkConverterLib.RenderJobMetaData meta = null;
            {
                XmlSerializer ser = new XmlSerializer(typeof(DeeptalkConverterLib.RenderJobMetaData));
                using (var reader = file.OpenText())
                {
                    meta = ser.Deserialize(reader) as DeeptalkConverterLib.RenderJobMetaData;
                    reader.Close();
                }
            }

            if (meta == null)
            {
                throw new ArgumentException("The file " + file.FullName + " contains XML that we can't convert to our meta data object!");
            }

            ///
            /// Now we have to do the complete conversation from the meta data to our results info!
            /// 

            var results = new DeepTalkRenderServiceLib.RenderMeetingTask.RenderResultsInfo();
            results.NumberOfTalks = meta.NumberOfTalks;
            results.SizeOfRender = (float) 10.0; // This is just bogus currently - woudl take too long to count!
            results.HowLongToNextUpdate = NextUpdateTimeCalculator.TimeToUpdate(meta.NumberOfUpdatedTalks, meta.MeetingStart, meta.MeetingEnd, DateTime.Now);
            if (results.HowLongToNextUpdate.Value.TotalSeconds == 0.0)
            {
                results.HowLongToNextUpdate = null;
            }

            results.Title = meta.MeetingTitle;
            results.MeetingStart = meta.MeetingStart;
            results.MeetingEnd = meta.MeetingEnd;

            return results;
        }
    }
}
